package com.tianhua.amis4j.service.ability;

import com.coderman.model.meta.GlobalConstant;
import com.coderman.model.meta.bean.PlantUMLApiContextBean;
import com.coderman.model.meta.bean.back.FieldBean;
import com.coderman.model.meta.bean.back.FieldExtendBean;
import com.coderman.model.meta.bean.back.ParamBean;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description:对扩展属性进行校验刷新
 * date: 2022/4/28
 *
 * @author fanchunshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class RefreshService {
    /**
     * 刷新属性内容，对apiParam进行属性区分
     * @param plantUMLApiContextBean
     */
    public void refresh(PlantUMLApiContextBean plantUMLApiContextBean){
        //将扩展字段内容提取出来
        plantUMLApiContextBean.getParamClassBeanList().forEach(paramBean -> {
            List<FieldBean> fieldList = paramBean.getFieldBeanList().stream().filter(fieldBean -> !fieldBean.isExtendFieldTag()).collect(Collectors.toList());
            List<FieldBean> extendFieldList = paramBean.getFieldBeanList().stream().filter(fieldBean -> fieldBean.isExtendFieldTag()).collect(Collectors.toList());
            paramBean.setFieldBeanList(fieldList);
            paramBean.setFieldExtendBeanMapList(buildExtendFieldMapList(extendFieldList));
        });

        Map<String,ParamBean> paramBeanMap = plantUMLApiContextBean.getParamClassBeanList().stream().collect(Collectors.toMap(ParamBean::getParamClassName,o -> o));


        /**
         * 针对提取的扩展字段信息更新参数模型
         */
        plantUMLApiContextBean.getApiBeanList().forEach(apiBean -> {
            ParamBean returnParamBean = apiBean.getReturnParam();
            if(returnParamBean != null){
                ParamBean newReturnParamBean = getParamModel(returnParamBean.getParamClassName(), plantUMLApiContextBean);
                if(newReturnParamBean != null){
                    apiBean.setReturnParam(newReturnParamBean);
                }
            }

            List<ParamBean> paramBeanList = apiBean.getParamBeanList();
            List<ParamBean> newParamBeanList = new ArrayList<>();
            for (ParamBean oldParam : paramBeanList){
                ParamBean newParam = paramBeanMap.get(oldParam.getParamClassName());
                if(newParam != null){
                    oldParam.setFieldBeanList(newParam.getFieldBeanList());
                    oldParam.setFieldExtendBeanMapList(newParam.getFieldExtendBeanMapList());
                    newParamBeanList.add(oldParam);
                }else {
                    newParamBeanList.add(oldParam);
                }
            }
            apiBean.setParamBeanList(newParamBeanList);
        });

        //构建参数属性扩展字段
        refreshParamField(plantUMLApiContextBean);
    }

    private Map<String,List<String>> buildExtendFieldMapList(List<FieldBean> extendFieldList){
        Map<String,List<String>> extendFieldMapList = new HashMap<>();
        for (FieldBean fieldBean : extendFieldList){
            List<String> list = extendFieldMapList.get(fieldBean.getFieldDoc());
            if(CollectionUtils.isEmpty(list)){
                list = Lists.newArrayList();
            }
            if(fieldBean.getFieldName().contains(",")){
                list.addAll(Lists.newArrayList(fieldBean.getFieldName().split(",")));
            }else {
                list.add(fieldBean.getFieldName());
            }
            extendFieldMapList.put(fieldBean.getFieldDesc(),list);
        }
        return extendFieldMapList;
    }



    /**
     * 根据api返回的参数来获取返回参数对象模型
     * @param paramClassName
     * @param plantUMLApiContextBean
     * @return
     */
    private ParamBean getParamModel(String paramClassName,PlantUMLApiContextBean plantUMLApiContextBean){
        if(paramClassName.contains("<")){
            if(paramClassName.endsWith(">")){
                paramClassName = paramClassName.replace(">","");
            }
            String [] paramClassArr = paramClassName.split("<");
            paramClassName = paramClassArr[1];
        }

        if(paramClassName.toLowerCase().endsWith(GlobalConstant.DTO)
        || paramClassName.toLowerCase().endsWith(GlobalConstant.VO)){
            String finalParamClassName = paramClassName;
            List<ParamBean> paramBeanList = plantUMLApiContextBean.getParamClassBeanList().stream().filter(paramBean -> paramBean.getParamClassName().equals(finalParamClassName)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(paramBeanList)){
                return paramBeanList.get(0);
            }
        }
        return null;
    }

    /**
     * 重新处理并构建每个属性的扩展属性信息
     * @param plantUMLApiContextBean
     */
    private void  refreshParamField(PlantUMLApiContextBean plantUMLApiContextBean){
        plantUMLApiContextBean.getParamClassBeanList().stream().forEach(paramBean -> {
            if(CollectionUtils.isNotEmpty(paramBean.getFieldBeanList())){
                paramBean.getFieldBeanList().forEach(fieldBean -> {
                    buildFieldExtend(fieldBean,paramBean.getFieldExtendBeanMapList());
                });
            }
        });
    }

    /**
     * 构建每个属性的扩展信息
     * @param fieldBean
     * @param fieldExtendBeanMapList
     */
    private void buildFieldExtend(FieldBean fieldBean, Map<String,List<String>> fieldExtendBeanMapList){

        FieldExtendBean fieldExtendBean = new FieldExtendBean();
        if(fieldExtendBeanMapList == null || fieldExtendBeanMapList.isEmpty()){
            fieldBean.setFieldExtendBean(new FieldExtendBean());
            return;
        }

        //必填标示
        List<String> notRequiredList = fieldExtendBeanMapList.get(GlobalConstant.NOT_REQUIRED_KEY_LIST);
        if(notRequiredList != null && !notRequiredList.contains(fieldBean.getFieldName())){
            fieldExtendBean.setRequired(true);
        }

        List<String> searchInPageList = fieldExtendBeanMapList.get(GlobalConstant.SEARCH_KEY_LIST);
        if(searchInPageList != null && searchInPageList.contains(fieldBean.getFieldName())){
            fieldExtendBean.setSearchInPage(true);
        }

        List<String> excludeInsertList = fieldExtendBeanMapList.get(GlobalConstant.EXCLUDE_INSERT);
        if(excludeInsertList == null || (excludeInsertList != null && !excludeInsertList.contains(fieldBean.getFieldName()))){
            fieldExtendBean.setInInsertForm(true);
        }


        List<String> excludeUpdateList = fieldExtendBeanMapList.get(GlobalConstant.EXCLUDE_UPDATE);
        if(excludeUpdateList == null || (excludeUpdateList != null && !excludeUpdateList.contains(fieldBean.getFieldName()))){
            fieldExtendBean.setInUpdateForm(true);
        }

        List<String> excludeDetailList = fieldExtendBeanMapList.get(GlobalConstant.EXCLUDE_DETAIL);
        if(excludeDetailList == null  || (excludeDetailList != null && !excludeDetailList.contains(fieldBean.getFieldName()))){
            fieldExtendBean.setInDetailForm(true);
        }

        List<String> excludePageList = fieldExtendBeanMapList.get(GlobalConstant.EXCLUDE_PAGE);
        if(excludePageList == null  || (excludePageList != null && !excludePageList.contains(fieldBean.getFieldName()))){
            fieldExtendBean.setInPageForm(true);
        }

        //如果指定了类型则将属性和表单元素类型绑定
        fieldExtendBeanMapList.forEach((k,v)->{
            if(!GlobalConstant.getInnerKey().contains(k) && v.contains(fieldBean.getFieldName())){
                fieldExtendBean.setInputType(k);
            }
        });



        fieldBean.setFieldExtendBean(fieldExtendBean);
    }
}
